import axios from 'axios'

/**
 * 封装axios请求
 * @param   url 请求路径
 * @param   params 请求字段
 * @param   type 请求方式
 * @author chencheng
 */
export default function ajax(url = '',params = {},type = 'post') {
    let promise;
    return new Promise((resolve, reject)=>{
        if (type.toLowerCase() === 'get'){
            let paramsStr = '';
            Object.keys(params).forEach(key=>{
                paramsStr += key + '=' + params[key] + '&';
            });
            if (paramsStr){
                paramsStr = paramsStr.substr(0,paramsStr.lastIndexOf('&'));
            }
            url = '?' + paramsStr;
            promise = axios.get(url);
        } else if(type.toLowerCase() === 'post'){
            promise = axios.post(url,params);
        }
        promise.then((response)=>{
            resolve(response.data);
        }).catch(error=>{
            reject(error);
        });
    })
}